import type { VNode, VNodeChild, Slots } from 'vue';
import { createTextVNode, Fragment } from 'vue';
/**
 * 将嵌套的vnode数组展开
 * @param vNodes
 * @param result
 * @returns
 */
export const flatten = (vNodes: VNodeChild[], result: VNode[] = []) => {
  vNodes.forEach((vNode) => {
    if (vNode === null) return;
    if (typeof vNode !== 'object') {
      if (typeof vNode === 'string' || typeof vNode === 'number') {
        result.push(createTextVNode(String(vNode)));
      }
      return;
    }
    if (Array.isArray(vNode)) {
      flatten(vNode, result);
      return;
    }
    if (vNode.type === Fragment) {
      if (vNode.children === null) return;
      if (Array.isArray(vNode.children)) {
        flatten(vNode.children, result);
      }
      // rawSlot
    } else if (vNode.type !== Comment) {
      result.push(vNode);
    }
  });
  return result;
};
/** 获取第一个子节点 */
export function getFirstSlotVNode(
  slots: Slots,
  slotName = 'default',
  props: unknown = undefined
): VNode | null {
  const slot = slots[slotName];
  if (!slot) {
    return null;
  }
  const slotContent = flatten(slot(props));
  // vue will normalize the slot, so slot must be an array
  if (slotContent.length === 1) {
    return slotContent[0];
  } else {
    console.warn(
      'getFirstSlotVNode',
      `slot[${slotName}] should have exactly one child`
    );
    return null;
  }
}

export const mergOwn = (target: object, source: object) => {
  for (const key in target) {
    if (target.hasOwnProperty(key)) {
      const sourceValue = (source as any)[key];
      if (sourceValue !== undefined) {
        (target as any)[key] = sourceValue;
      }
    }
  }
  return target;
};
